package com.sanjiahantang.youjiaclient.module.pdf.views.impl;

import android.Manifest;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.OpenableColumns;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;


import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.listener.OnPageErrorListener;
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;
import com.github.barteksc.pdfviewer.util.FitPolicy;
import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.youjiaclient.R;
import com.sanjiahantang.youjiaclient.base.BaseMvpActivity;
import com.sanjiahantang.youjiaclient.config.ConfigValue;
import com.sanjiahantang.youjiaclient.config.StaticValue;
import com.sanjiahantang.youjiaclient.module.me.contract.beans.ContractBean;
import com.sanjiahantang.youjiaclient.module.pdf.beans.PdfInfoBean;
import com.sanjiahantang.youjiaclient.module.pdf.views.PdfBaseView;
import com.sanjiahantang.youjiaclient.module.pdf.presenters.PDFPresenter;
import com.sanjiahantang.youjiaclient.utils.L;
import com.sanjiahantang.youjiaclient.utils.SDCardUtils;
import com.sanjiahantang.youjiaclient.utils.SystemUtil;

import java.io.File;

/**
 * Created by yan on 2017/12/25.
 */

public class PDFShowActivity extends BaseMvpActivity<PdfBaseView, PDFPresenter> implements PdfBaseView, PDFPresenter.SucssesCallBack,
        OnPageChangeListener, OnLoadCompleteListener, OnPageErrorListener, View.OnClickListener {

    private PDFView pdfView;

    //pdf文件全路径
    private String filepath;

    private Intent intent;


    @Override
    public PDFPresenter initPresenter() {
        return new PDFPresenter();
    }

    @Override
    public void initView() {
        setContentView(R.layout.pdf_view);
        pdfView = (PDFView) this.findViewById(R.id.pdfView);
        intent=this.getIntent();
        TextView title = (TextView) findViewById(R.id.title);
        title.setText(intent.getStringExtra(KEY_CONTRACTNAME));
        View back = findViewById(R.id.back);
        back.setOnClickListener(this);
        String contractCode = intent.getStringExtra(StaticValue.KEY_CONTRACT);
        if (!contractCode.isEmpty()) {
            presenter.loadData(this, contractCode, this);
        }
    }

    @Override
    public void showProgress(@NonNull Context context) {
        super.showProgress($this);
    }

    @Override
    public void initData() {


    }

    @Override
    public void sucsses(String filename) {
        if (SystemUtil.getDeviceBrand().equals("vivo")) {
            File file = new File(filename);
            Intent intent = new Intent("android.intent.action.VIEW");
            intent.addCategory("android.intent.category.DEFAULT");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri uri = Uri.fromFile(file);
            intent.setDataAndType(uri, "application/pdf");
            Intent.createChooser(intent, "Open File");
            startActivity(intent);
            setResult(3, getIntent());
            finish();

        } else {
            openFile(filename);
        }
    }

    private void openFile(String filename) {

        filepath = filename;

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            displayFromFile(filename);
        } else {
            if (this.checkSelfPermission(
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                }, PdfBaseView.REQUEST_CODE);
            } else {
                displayFromFile(filename);
            }
        }
    }

    /**
     * 打开sdcard里的文件
     *
     * @param path
     */
    private void displayFromFile(String path) {
        File file = new File(path);

        if (file.exists()) {
            pdfView.fromFile(file)
                    .defaultPage(0)
                    .onPageChange(this)
                    .enableAnnotationRendering(true)
                    .onLoad(this)
                    .scrollHandle(new DefaultScrollHandle(this))
                    .spacing(10) // in dp
                    .onPageError(this)
                    .pageFitPolicy(FitPolicy.BOTH)
                    .load();

        } else {
            Utils.showToast(this, "该合同不存在");
        }
    }


    @Override
    public void showProgress() {
        super.showProgress($this);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        presenter.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE) {
            displayFromFile(filepath);
        }
    }

    @Override
    public void onPageChanged(int page, int pageCount) {

    }

    @Override
    public void loadComplete(int nbPages) {

    }

    @Override
    public void onPageError(int page, Throwable t) {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                setResult(3, intent);
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            setResult(3, intent);
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }
}
